

import urllib.parse

import requests
import re as c

from cookie import Cookie
from readFile import ReadFlie


class item():
    #服务器地址
    url='59.215.206.188'
    #综合受理系统
    system='zhslzy'
    cookie=Cookie().cookie()
    head = {
        "Host": "{}".format(url),
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "X-Requested-With": "XMLHttpRequest",
        "Content-Length": "1734",
        "Origin": "{}".format(url),
        "Connection": "keep-alive",
        #"Referer": "http://61.243.4.18:88/zhslzy//accept/dockingcenter/itemconnection/show?id=09CB9ACFE7EC4675A01C0246B417A68B&itemcode=520300-N-XK-00101&version=1&type=&page=1&rows=10",
        "Cookie": "{}".format(cookie),
    }

    # 加密
    def quote(self, text):
        x = urllib.parse.quote(text)
        return x

    # 查询事项基本信息并返回
    def query(self, itemname,orgcode):
        itemCode = ''
        url = 'http://{}/{}/accept/dockingcenter/baseitem/itemQuery?queryType='.format(self.url,self.system)
        head={
            "Host": "{}".format(self.url),
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0",
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate",
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": "117",
            "Origin": "http://{}".format(self.url),
            "Connection": "keep-alive",
            #"Referer": "http://61.243.4.18:88/zhslzy/accept/dockingcenter/itemconnection/index",
            "Cookie": "{}".format(self.cookie),
        }
        data = {
            "page": "1",
            "rows": "10",
            "icode": "",
            #"icode": "520300-N-XK-00101",
            "iname": "{}".format(itemname),
            #"iname": "",
            "orgName": "",
            "orgCode": "",
            "type": "",
            "regionName": "",
            "regionCode": "{}".format(orgcode),
            "assort": "",
        }
        x = requests.post(url, headers=head, data=data).json()

        for i in range(x['records']):
            # print(x['rows'][i])
            if x['rows'][i]['cell']['NAME'] == itemname:
                # 事项ID
                itemId = x['rows'][i]['cell']['ID']
                # 事项名称
                itemName = self.quote(self.quote(x['rows'][i]['cell']['NAME']))
                # 事项编码
                itemCode = x['rows'][i]['cell']['CODE']
                #
                INNER_CODE = x['rows'][i]['cell']['INNER_CODE']
                # 目录编码
                folderCode = x['rows'][i]['cell']['FOLDER_ID']
                # 目录名称
                folderName = self.quote(x['rows'][i]['cell']['FOLDER_NAME'])
                # 区划编码
                areaCode = x['rows'][i]['cell']['REGION_CODE']
                # 区划名
                areaName = x['rows'][i]['cell']['REGION_NAME']
                # 部门名
                organName = x['rows'][i]['cell']['ORG_NAME']
                # 部门编码
                organCode = x['rows'][i]['cell']['ORG_CODE']
                # 承诺时限
                agreeTime = x['rows'][i]['cell']['AGREE_TIME']
                # 法定时限
                itemLawTime = x['rows'][i]['cell']['LAW_TIME']
                #print("-----------打query返回--------")
                #print(itemId, itemName, itemCode, INNER_CODE, folderCode, folderName, areaCode, areaName, organName, organCode, )
                return itemId, itemName, itemCode, INNER_CODE, folderCode, folderName, areaCode, areaName, organName, organCode, agreeTime, itemLawTime
                break

    # 获取事项现有配置  返回 #确认受理时限（工作日） #承诺时限  传入itemid，itemcode
    def queryItemNow(self, itemid, itemcode):
        # 接收query返回的数据
        url = 'http://{}/{}//accept/dockingcenter/itemconnection/itemshow?itemid={}&itemcode={}'.format(self.url,self.system,itemid,
                                                                                                                itemcode)
        #url="http://61.243.4.18:88/zhslzy/accept/dockingcenter/itemconnection/itemshow?itemid=9ACCCB51145A4D859E9F731D0D8D195C&itemcode=520300-051-XK-00821&version=22"
        head={
            "Host": "{}".format(self.url),
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0",
            "Accept": "text/html, */*; q=0.01",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate",
            "X-Requested-With": "XMLHttpRequest",
            "Connection": "keep-alive",
            #"Referer": "http://61.243.4.18:88/zhslzy/accept/dockingcenter/itemconnection/show?id=9ACCCB51145A4D859E9F731D0D8D195C&itemcode=520300-051-XK-00821&version=22&type=&page=1&rows=10",
            "Cookie":"{}".format(self.cookie)
        }
        x = requests.get(url,headers=head).text

        # #a = re.findall('confirmAcceptTime(.*?)datatype',x)
        # 确认受理时限（工作日）
        a = c.findall('value="(.*?)" datatype=', x)[0]
        # print("------打印配置详情并返回确认受理时限（工作日）---------")

        return a

    # 更新事项配置
    def updata(self,orgcode,事项名称,办件类型,服务对象,表单版本,表单名称,表单ID,即来即办,事项类别,系统ID,系统名称,):
        try:
            #print(事项名称,办件类型,服务对象,表单版本,表单名称,表单ID,即来即办,事项类别,系统名称,系统ID)

            #### "itemTime":"1"  formId
            #print("------调用qurey-----")
            queryRe = self.query(事项名称,orgcode)
            # print(queryRe)
            # print("------update------")
            #print(queryRe[0], queryRe[2])
            #print("------2-------")

            queryItemNowre = self.queryItemNow(queryRe[0], queryRe[2])
            # print(queryItemNowre)
            确认受理时限 = queryItemNowre[0]

            data = {"itemId": "{}".format(queryRe[0]), "itemName": "{}".format(queryRe[1]),
                    "itemCode": "{}".format(queryRe[2]),
                    "innerCode": "{}".format(queryRe[3]), "folderCode": "{}".format(queryRe[4]),
                    "folderName": "{}".format(queryRe[5]),
                    "areaCode": "{}".format(queryRe[6]), "areaName": "{}".format(queryRe[7]),
                    # 未核对
                    "itemTime": "1",
                    "organName": "{}".format(queryRe[8]), "organCode": "{}".format(queryRe[9]),
                    ################################  以上为事项基本信息    ###############################

                    # 指定项
                    #ID、名称反向存放，暂未核对原因
                    "systemId": "{}".format(系统ID), "systemName": "{}".format(系统名称), "formId": "{}".format(表单ID),
                    # 未核对
                    "caseInfo": "", "stage": "",
                    # 指定项
                    "formNameNew": "{}".format(表单名称), "publishVersionId": "", "formVersion": "{}".format(表单版本),
                    # 办理对象
                    "serviceObjectType": "{}".format(服务对象),

                    "supportAllArea": "1",
                    # 网办是否预审
                    "pre": "1",
                    "isSms": "1", "businessType": "0",
                    "priority": "0000",
                    # 收件、受理权限    0受理、1收件
                    "handleAuthority": "{}".format(办件类型),
                    #
                    "isDockedOnline": "0", "isJDTB": "0",

                    # 是否即来即办   1 是
                    "isImmedFinish": "{}".format(即来即办),
                    #
                    "isLingZhen": "0", "isSign": "0", "isChiefAccept": "0", "isOften": "0", "isSupportEms": "0",
                    "isMultiSituation": "0", "haveCertificate": "0", "handleName": "", "handleCode": "",
                    #预警时限
                    "warningTime": "0",
                    # 承诺时限
                    "agreeTime": "{}".format(queryRe[10]),
                    #

                    "sybmol": "", "target": "", "targetUrl": "", "ifNewTab": "0",
                    "appCode": "", "appUrl": "", "isLoginSso": "0", "ssoMode": "1", "ssoType": "0",
                    "isMaterialVerification": "0",
                    #是否自动收件受理
                    "isAutoCommit": "0",
                    "isAutoCommitSms": "0", "isPush": "1", "windowMode": "1",
                    # 确认受理时限（工作日）
                    "confirmAcceptTime": "{}".format(确认受理时限),
                    #区别一二三类
                    "handleMode": "{}".format(事项类别),

                    "isFinishPick": "1", "isFinishCheckMaterial": "0", "regionName": "",
                    "regionCode": "", "isAllDeal": "0", "allDealHandleAuthority": "0", "levelType": "null",
                    "itemOtherName": "",
                    # 法定时限
                    "itemLawTime": "{}".format(queryRe[11]),
                    #
                    "itemTheme": "", "continuous": "0",
                    #是否展示表单
                    "showForm": "1",
                    "personSubjectTemplate": "",
                    "companySubjectTemplate": "", "isFormSSO": "0", "appCodeFormSSO": "", "appUrlFormSSO": "",
                    "saveBtnSource": "0",
                    "dockingType": "0", "isSensitive": "0", "popularName": "",
                    "titleName": "%25E5%2585%25B6%2520%2520%2520%2520%2520%25E4%25BB%2596",
                    "shoujianIsPrint": "1"}


            #计算json长度
            test = "'" + str(data)
            test = str(test) + "'"
            length = len(test.encode('utf-8'))

            headder={
                "Host": "{}".format(self.url),
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0",
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                "Accept-Encoding": "gzip, deflate",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "X-Requested-With": "XMLHttpRequest",
                "Content-Length": "{}".format(length),
                "Origin": "http://{}".format(self.url),
                "Connection": "keep-alive",
                #"Referer": "http://61.243.4.18:88/zhslzy/accept/dockingcenter/itemconnection/show?id=9ACCCB51145A4D859E9F731D0D8D195C&itemcode=520300-051-XK-00821&version=22&type=&page=1&rows=10",
                "Cookie": "{}".format(self.cookie),

            }


            url = 'http://{}/{}/accept/dockingcenter/itemconnection?method=save'.format(self.url,self.system)
            x = requests.post(url, headers=headder, json=data)

            print(orgcode+">"+事项名称 + ":" + "返回状态为" + str(x.status_code))

        except:

            print(orgcode+">"+事项名称+"--"+"出错了")

    def loop(self,orgcode):
        x = ReadFlie().readFile()
        for i in range(len(x[0])):

            事项名称 = x[0][i]
            行使层级 = x[1][i]
            办件类型 =x[2][i]
            服务对象 = x[3][i]
            事项类别 =x[4][i]
            表单版本 = x[5][i]
            表单名称 =x[6][i]
            表单ID = x[7][i]
            即来即办=x[8][i]
            系统ID=x[9][i]
            系统名称=x[10][i]
            #print(事项名称,办件类型,服务对象,表单版本,表单名称,表单ID,即来即办)
            self.updata(orgcode,事项名称,办件类型,服务对象,表单版本,表单名称,表单ID,即来即办,事项类别,系统ID,系统名称)
    def startLoop(self):
        org={

            "遵义市":"520300",
            # # #"直属机关":"520300O",
            # "红花岗区":"520302",
            # "汇川区":"520303",
            # "播州区":"520321",
            # "桐梓县":"520322",
            # "绥阳县":"520323",
            # "正安县":"520324",
            # "道真县":"520325",
            # "务川县":"520326",
            # "凤冈县":"520327",
            # "湄潭县":"520328",
            # "余庆县":"520329",
            # "习水县":"520330",
            # "赤水市":"520381",
            # "仁怀市":"520382",
            # "新蒲新区":"520383",

            }


        for i in org:
            item().loop(org[i])

item().startLoop()
#item().updata('测试')
#item().queryItemNow("9ACCCB51145A4D859E9F731D0D8D195C","520300-051-XK-00821")
#item().loop()
#item().query("临时居民身份证办理","520300")
